//
//  YWSelectMeterReadingEquipmentTableViewController.m
//  maintain
//
//  Created by kyo on 16/12/8.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWSelectMeterReadingEquipmentTableViewController.h"
#import "UIColor+CustomColors.h"
#import "YWMacro.h"
#import "YWCommonTool.h"
#import "MJRefresh.h"
#import "YWLoginTool.h"
#import "UIScrollView+EmptyDataSet.h"

#import "DOPDropDownMenu.h"

#import "YWBuilding.h"
#import "YWApartment.h"
#import "YWFloor.h"
#import "YWLocation.h"
#import "YWBuildingManager.h"
#import "YWEquipment.h"
#import "YWEquipmentType.h"
#import "YWEquipmentManager.h"
#import "YWMeterReadingManager.h"
#import "YWSelectBuildingTableViewController.h"

@interface YWSelectMeterReadingEquipmentTableViewController ()<DZNEmptyDataSetDelegate, DZNEmptyDataSetSource,DOPDropDownMenuDataSource,DOPDropDownMenuDelegate,YWSelectBuildingTableViewControllerDelegate>{
    YWBuilding *currentBuilding;
    YWApartment *currentApartment;
    YWFloor *currentFloor;
    YWLocation *currentLocation;
    YWEquipmentType *currentEquipmentType;
    
    NSInteger page;
    
    YWEquipment *currentEquipment;
    NSIndexPath *lastIndexPath;
}
@property (nonatomic, strong) DOPDropDownMenu *menu;
@property (nonatomic, strong) NSMutableArray *menuDataArray;

@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, strong) NSArray *allBuildings;
@property (nonatomic, strong) YWEquipmentType *waterMeterEquipmentType;
@property (nonatomic, strong) YWEquipmentType *electricMeterEquipmentType;
@property (nonatomic, strong) YWEquipmentType *gasMeterEquipmentType;
@end

@implementation YWSelectMeterReadingEquipmentTableViewController
//- (instancetype)init{
//    return [super  initWithStyle:UITableViewStyleGrouped];
//}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"选择设备";
    
    [self setupDataSource];
    // 创建menu 第一次显示 不会调用点击代理，可以用这个手动调用
    [self.menu selectDefalutIndexPath];
    
    [self initTableView];
}

- (void)setupDataSource{
    page = 1;
    if (!currentBuilding) {
        currentBuilding = [self.allBuildings count] ? self.allBuildings[0] : nil;
    }
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:currentBuilding.buildingName?:@"楼盘" style:UIBarButtonItemStylePlain target:self action:@selector(selectBuildingEvent:)];
    currentEquipmentType = self.waterMeterEquipmentType;
    
    NSArray *equipments = [[YWEquipmentManager shareManager] equipmentsWithBuildingId:currentBuilding.buildingId ApartmentId:0 floorId:0 locationId:0 eqipmentSubSystemType:0 equipmentTypeId:currentEquipmentType.equipmentTypeId page:page];
    [self.dataSource addObjectsFromArray:equipments];
}

- (NSMutableArray *)menuDataArray{
    if (!_menuDataArray) {
        _menuDataArray = [NSMutableArray array];
        
        NSMutableArray *apartmentMut = [NSMutableArray array];
        YWApartment *apartment = [[YWApartment alloc] init];
        NSString *apartmentShowName = [YWLoginTool apartmentShowName];
        apartment.apartmentName = apartmentShowName.length? apartmentShowName:@"楼栋";
        [apartmentMut addObject:apartment];
        
        NSArray *apartmentArray = [[YWBuildingManager shareManager] apartmentWithbuildingId:currentBuilding.buildingId];
        [apartmentMut addObjectsFromArray:apartmentArray];
        
        NSMutableArray *floorMut = [NSMutableArray array];
        YWFloor *floor = [[YWFloor alloc] init];
        NSString *floorShowName = [YWLoginTool floorShowName];
        floor.floorName = floorShowName.length? floorShowName:@"楼层";
        [floorMut addObject:floor];
        
        NSMutableArray *locationMut = [NSMutableArray array];
        YWLocation *location = [[YWLocation alloc] init];
        NSString *locationShowName = [YWLoginTool locationShowName];
        location.locationName = locationShowName.length? locationShowName:@"位置";
        [locationMut addObject:location];
        
        NSMutableArray *typeMut = [NSMutableArray array];
        [typeMut addObject:self.waterMeterEquipmentType];
        [typeMut addObject:self.electricMeterEquipmentType];
        [typeMut addObject:self.gasMeterEquipmentType];
        
        [_menuDataArray addObject:apartmentMut];
        [_menuDataArray addObject:floorMut];
        [_menuDataArray addObject:locationMut];
        [_menuDataArray addObject:typeMut];
        
    }
    return _menuDataArray;
}

- (DOPDropDownMenu *)menu{
    if (!_menu) {
        DOPDropDownMenu *menu = [[DOPDropDownMenu alloc] initWithOrigin:CGPointMake(0, 64) andHeight:44];
        menu.delegate = self;
        menu.dataSource = self;
        _menu = menu;
    }
    return _menu;
}

- (void)initTableView{
    self.tableView.backgroundColor = [UIColor customBackgroudColor];
    self.tableView.separatorColor = [UIColor customLineColor];
    self.tableView.rowHeight = 52.0f;
    self.tableView.sectionFooterHeight = 1.0;
    self.tableView.emptyDataSetDelegate = self;
    self.tableView.emptyDataSetSource = self;
    self.tableView.tableFooterView = [[UIView alloc] init];
    
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(refreshFootor)];
    self.tableView.mj_footer.automaticallyHidden = YES;
}

- (void)refreshFootor{
    page++;
    [self.dataSource removeAllObjects];
    NSArray *equipments = [[YWEquipmentManager shareManager] equipmentsWithBuildingId:currentBuilding.buildingId ApartmentId:currentApartment.apartmentId floorId:currentFloor.floorId locationId:currentLocation.locationId eqipmentSubSystemType:0 equipmentTypeId:currentEquipmentType.equipmentTypeId page:page];
    [self.dataSource addObjectsFromArray:equipments];
    
    [self.tableView.mj_footer endRefreshing];
    [self.tableView reloadData];
}

- (NSInteger)numberOfColumnsInMenu:(DOPDropDownMenu *)menu
{
    return self.menuDataArray.count;
}

- (NSInteger)menu:(DOPDropDownMenu *)menu numberOfRowsInColumn:(NSInteger)column
{
    return column<0 ? 0 : [_menuDataArray[column] count];
}

- (NSString *)menu:(DOPDropDownMenu *)menu titleForRowAtIndexPath:(DOPIndexPath *)indexPath
{
    if (indexPath.column == 0) {
        YWApartment *apartment = _menuDataArray[indexPath.column][indexPath.row];
        return apartment.apartmentName;
    }else if (indexPath.column == 1){
        YWFloor *floor = _menuDataArray[indexPath.column][indexPath.row];
        return floor.floorName;
    }else if (indexPath.column == 2){
        YWLocation *location = _menuDataArray[indexPath.column][indexPath.row];
        return location.locationName;
    }else if (indexPath.column ==3){
        YWEquipmentType *equipmentType = _menuDataArray[indexPath.column][indexPath.row];
        return equipmentType.equipmentTypeName;
    }
    return nil;
}

//- (NSInteger)menu:(DOPDropDownMenu *)menu numberOfItemsInRow:(NSInteger)row column:(NSInteger)column
//{
//    return 0;
//}
//
//- (NSString *)menu:(DOPDropDownMenu *)menu titleForItemsInRowAtIndexPath:(DOPIndexPath *)indexPath
//{
//    return nil;
//}

- (void)menu:(DOPDropDownMenu *)menu didSelectRowAtIndexPath:(DOPIndexPath *)indexPath
{
    BOOL needSelect = NO;
    if (indexPath.column == 0) {
        YWApartment *apartment = _menuDataArray[indexPath.column][indexPath.row];
        if (currentApartment.apartmentId!=apartment.apartmentId) {
            needSelect = YES;
            currentApartment = apartment;
            currentFloor = nil;
            currentLocation = nil;
            
            NSMutableArray *floorMut = [NSMutableArray array];
            YWFloor *floor = [[YWFloor alloc] init];
            NSString *floorShowName = [YWLoginTool floorShowName];
            floor.floorName = floorShowName.length? floorShowName:@"楼层";
            [floorMut addObject:floor];
            
            NSArray *floorArray = [[YWBuildingManager shareManager] floorWithApartmentId:currentApartment.apartmentId];
            [floorMut addObjectsFromArray:floorArray];
            
            [_menuDataArray replaceObjectAtIndex:1 withObject:floorMut];
            
            //[_menu reloadData];
            //[_menu selectIndexPath:indexPath];
            DOPIndexPath *reloadIndexPath = [DOPIndexPath indexPathWithCol:1 row:0];
            [_menu selectIndexPath:reloadIndexPath];
            reloadIndexPath = [DOPIndexPath indexPathWithCol:2 row:0];
            [_menu selectIndexPath:reloadIndexPath];
        }
        
    } else if (indexPath.column == 1){
        YWFloor *floor = _menuDataArray[indexPath.column][indexPath.row];
        if (currentFloor.floorId != floor.floorId) {
            needSelect = YES;
            currentFloor = floor;
            currentLocation = nil;
            
            NSMutableArray *locationMut = [NSMutableArray array];
            YWLocation *location = [[YWLocation alloc] init];
            NSString *locationShowName = [YWLoginTool locationShowName];
            location.locationName = locationShowName.length? locationShowName:@"位置";
            [locationMut addObject:location];
            
            NSArray *locationArray = [[YWBuildingManager shareManager] locationWithFloorId:currentFloor.floorId];
            [locationMut addObjectsFromArray:locationArray];
            
            [_menuDataArray replaceObjectAtIndex:2 withObject:locationMut];
            
            //[_menu reloadData];
            //[_menu selectIndexPath:indexPath];
            DOPIndexPath *reloadIndexPath = [DOPIndexPath indexPathWithCol:2 row:0];
            [_menu selectIndexPath:reloadIndexPath];
        }
    }else if (indexPath.column == 2){
        YWLocation *location = _menuDataArray[indexPath.column][indexPath.row];
        if (currentLocation.locationId != location.locationId) {
            needSelect = YES;
            currentLocation = location;
        }
    }else if (indexPath.column == 3){
        needSelect = YES;
        YWEquipmentType *equipmentType = _menuDataArray[indexPath.column][indexPath.row];
        currentEquipmentType = equipmentType?:nil;
    }
    if (needSelect) {
        page = 1;
        [self rightNowSelect];
    }
}


#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.dataSource count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *reuseIdentifier = @"YWSelectMeterReadingEquipmentCellReuseIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (cell==nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuseIdentifier];
        cell.textLabel.font = kContentFont;
        cell.detailTextLabel.font = KSmallContentFont;
        cell.detailTextLabel.textColor = [UIColor customTextGrayColor];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    YWEquipment *equipment = _dataSource[indexPath.row];
    cell.textLabel.text = equipment.equipmentName?:@"";
    cell.detailTextLabel.text = [[YWBuildingManager shareManager] equipmentLocationNobuilding:equipment]?:@"位置:无";
    return cell;
}

- (UIView*)tableView:(UITableView*)tableView viewForHeaderInSection:(NSInteger)section
{
    return _menu;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 44;
}

//-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
//    YWEquipment *equipment = _dataSource[indexPath.row];
//    if ([equipment.equipmentId isEqualToString:currentEquipment.equipmentId]) {
//        [tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
//    }else{
//        [tableView deselectRowAtIndexPath:indexPath animated:NO];
//    }
//}

//- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;
//}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    YWEquipment *equipment = _dataSource[indexPath.row];
    if (![equipment.equipmentId isEqualToString:currentEquipment.equipmentId]) {
        currentEquipment = equipment;
    }
    [self doMeterReading:nil];
//    if (lastIndexPath) {
//        [tableView deselectRowAtIndexPath:lastIndexPath animated:NO];
//    }else{
//        [self.tableView reloadData];
//    }
    lastIndexPath = indexPath;
}

//- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
//    YWEquipment *equipment = _dataSource[indexPath.row];
//    if ([equipment.equipmentId isEqualToString:currentEquipment.equipmentId]) {
//        currentEquipment = nil;
//    }
////    lastIndexPath = nil;
//}

- (void)rightNowSelect{
    [self.dataSource removeAllObjects];
    NSArray *equipments = [[YWEquipmentManager shareManager] equipmentsWithBuildingId:currentBuilding.buildingId ApartmentId:currentApartment.apartmentId floorId:currentFloor.floorId locationId:currentLocation.locationId eqipmentSubSystemType:0 equipmentTypeId:currentEquipmentType.equipmentTypeId page:page];
    [self.dataSource addObjectsFromArray:equipments];
    
    [self.tableView reloadData];
}

- (void)selectBuildingEvent:(id)sender{
    YWSelectBuildingTableViewController *selectBuildingVC = [[YWSelectBuildingTableViewController alloc] init];
    selectBuildingVC.delegate = self;
    selectBuildingVC.ownBuilding = currentBuilding;
    [self.navigationController pushViewController:selectBuildingVC animated:YES];
}

#pragma mark - YWSelectBuildingTableViewControllerDelegate
- (void)popSelectedBuilding:(YWBuilding *)building{
    if (building && ![currentBuilding.buildingId isEqualToString:building.buildingId]) {
        [self.navigationItem.rightBarButtonItem setTitle:building.buildingName?:@"楼盘"];
        currentBuilding = building;
        currentApartment = nil;
        currentFloor = nil;
        currentLocation = nil;
        currentEquipment = nil;
        
        //重新构建数据
        [self.dataSource removeAllObjects];
        [self setupDataSource];
        _menuDataArray = nil;
        // 创建menu 第一次显示 不会调用点击代理，可以用这个手动调用
        [self.menu selectDefalutIndexPath];
        
        [self.tableView reloadData];
    }
}

- (void)doMeterReading:(id)sender{
    //点确定
    if (currentEquipment) {
        if (currentEquipment.equipmentTypeId == [[YWMeterReadingManager shareManager] waterMeterEquipmentTypeId] || currentEquipment.equipmentTypeId == [[YWMeterReadingManager shareManager] electricMeterEquipmentTypeId] || currentEquipment.equipmentTypeId == [[YWMeterReadingManager shareManager] gasMeterEquipmentTypeId]) {
            if (_meterReadingBlock) {
                _meterReadingBlock(currentEquipment);
            }
        }else{
            [YWCommonTool showTextHUDWithContent:@"请选择一个可抄表设备"];
        }
    }else{
        [YWCommonTool showTextHUDWithContent:@"请选择一个可抄表设备"];
    }
}

- (NSArray *)allBuildings{
    if (!_allBuildings) {
        _allBuildings = [[NSArray alloc] initWithArray:[[YWBuildingManager shareManager] allBuilding]];
    }
    return _allBuildings;
}
- (YWEquipmentType *)waterMeterEquipmentType{
    if (!_waterMeterEquipmentType) {
        NSInteger equipmentTypeId = [[YWMeterReadingManager shareManager] waterMeterEquipmentTypeId];
        _waterMeterEquipmentType = [[YWEquipmentType alloc] init];
        _waterMeterEquipmentType.equipmentTypeId = equipmentTypeId;
        NSString *equipmentTypeName = [[YWEquipmentManager shareManager] equipmentTypeNameWithTypeId:equipmentTypeId];
        _waterMeterEquipmentType.equipmentTypeName = equipmentTypeName;
    }
    return _waterMeterEquipmentType;
}
- (YWEquipmentType *)electricMeterEquipmentType{
    if (!_electricMeterEquipmentType) {
        NSInteger equipmentTypeId = [[YWMeterReadingManager shareManager] electricMeterEquipmentTypeId];
        _electricMeterEquipmentType = [[YWEquipmentType alloc] init];
        _electricMeterEquipmentType.equipmentTypeId = equipmentTypeId;
        NSString *equipmentTypeName = [[YWEquipmentManager shareManager] equipmentTypeNameWithTypeId:equipmentTypeId];
        _electricMeterEquipmentType.equipmentTypeName = equipmentTypeName;
    }
    return _electricMeterEquipmentType;
}
- (YWEquipmentType *)gasMeterEquipmentType{
    if (!_gasMeterEquipmentType) {
        NSInteger equipmentTypeId = [[YWMeterReadingManager shareManager] gasMeterEquipmentTypeId];
        _gasMeterEquipmentType = [[YWEquipmentType alloc] init];
        _gasMeterEquipmentType.equipmentTypeId = equipmentTypeId;
        NSString *equipmentTypeName = [[YWEquipmentManager shareManager] equipmentTypeNameWithTypeId:equipmentTypeId];
        _gasMeterEquipmentType.equipmentTypeName = equipmentTypeName;
    }
    return _gasMeterEquipmentType;
}

- (NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    if (lastIndexPath) {
        [self.tableView deselectRowAtIndexPath:lastIndexPath animated:YES];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
